package models

import (
	"time"

	"gorm.io/gorm"
)

// PointsHistory 积分历史记录模型
type PointsHistory struct {
	gorm.Model
	UserID      int       `json:"user_id" gorm:"not null"`      // 用户ID
	Points      int       `json:"points" gorm:"not null"`       // 积分变化值（正数表示增加，负数表示减少）
	Description string    `json:"description" gorm:"size:255"`   // 积分变化描述
	CreatedAt   time.Time `json:"created_at"`                   // 创建时间
}

// AddPointsHistory 添加积分历史记录
func AddPointsHistory(userID int, points int, description string) error {
	record := PointsHistory{
		UserID:      userID,
		Points:      points,
		Description: description,
		CreatedAt:   time.Now(),
	}
	return GetDB().Create(&record).Error
}

// GetPointsHistoryByUserID 根据用户ID获取积分历史记录
func GetPointsHistoryByUserID(userID int) ([]PointsHistory, error) {
	var histories []PointsHistory
	err := GetDB().Where("user_id = ?", userID).Order("created_at DESC").Find(&histories).Error
	return histories, err
}

// GetPointsRanking 获取积分排行榜
func GetPointsRanking(limit int) ([]User, error) {
	var ranking []User
	err := GetDB().Where("status = ?", "active").Order("points DESC").Limit(limit).Find(&ranking).Error
	return ranking, err
}